<template>
  <div class="nav_bar">
    <el-menu
        :collapse="false"
        :default-active="activeMenu"
        :default-openeds="defaultOpeneds"
        class="el-menu-vertical-demo"
        @close="handleClose"
        @open="handleOpen"
    >
      <!-- 动态渲染菜单 -->
      <template v-for="route in menuRoutes">
        <!-- 如果有子路由，渲染为子菜单 -->
        <el-submenu v-if="route.children && route.children.length" :index="route.name">
          <template slot="title">
            <i class="el-icon-location"></i>
            <span>{{ route.meta ? route.meta.title : '未命名' }}</span>
          </template>
          <el-menu-item
              v-for="child in route.children"
              :key="child.name"
              :index="child.name"
              @click="handleMenuItemClick(child)"
          >
            <span>{{ child.meta.title }}</span>
          </el-menu-item>
        </el-submenu>
        <!-- 如果没有子路由，渲染为普通菜单项 -->
        <el-menu-item v-else :index="route.name">
          <i class="el-icon-menu"></i>
          <span slot="title">{{ route.meta.title }}</span>
        </el-menu-item>
      </template>
    </el-menu>
  </div>
</template>

<script>
export default {
  name: "NavBar",
  data() {
    return {
      isCollapse: true,
      menuRoutes: [], // 用于存储过滤后的路由
      defaultOpeneds: [], // 默认展开的菜单项
      activeMenu: '' // 当前高亮的菜单项
    };
  },
  created() {
    // 动态获取路由并过滤出有 meta 键的路由
    const filterRoutes = (routes) => {
      return routes
          .filter(route => route.meta || (route.children && route.children.some(child => child.meta))) // 过滤出有 meta 键的路由或子路由
          .map(route => ({
            ...route,
            children: route.children ? filterRoutes(route.children) : [] // 递归处理子路由
          }));
    };
    const newRouter = filterRoutes(this.$router.options.routes);
    this.$set(this, 'menuRoutes', newRouter);

    // 设置默认展开的菜单项
    this.defaultOpeneds = newRouter.map(route => route.name);

    // 监听路由变化，设置高亮菜单
    this.setActiveMenu();
  },
  watch: {
    // 监听路由变化，动态设置高亮菜单
    '$route': 'setActiveMenu'
  },
  methods: {
    // 设置当前高亮的菜单项
    setActiveMenu() {
      const route = this.$route;
      const matched = route.matched;
      if (matched.length) {
        // 获取当前路由的 name，设置为高亮菜单项
        this.activeMenu = matched[matched.length - 1].name;
      }
    },
    handleMenuItemClick(child) {
      // 阻止事件冒泡
      event.stopPropagation();
      // 跳转到对应路由
      this.$router.push({name: child.name});
    },
    handleOpen(key, keyPath) {
      console.log(key, keyPath, '******');
      // 一级菜单不跳转
      if (keyPath.length === 1) {
        return;
      }
      // 二级菜单跳转
      this.$router.push({name: key});
    },
    handleClose(key, keyPath) {
      console.log(key, keyPath);
    }
  }
};
</script>

<style lang="scss" scoped>
.nav_bar {
  width: 15vw;
  min-height: 92vh;
  box-shadow: 0px 8px 10px rgba(0, 0, 0, 0.1);
}

.el-menu-vertical-demo:not(.el-menu--collapse) {
  width: 100%;
  min-height: 92vh;
}
</style>
